import { Restart } from '../other/restart.js';
import dns from 'dns';

// 仅在 pm2 启动时候生效
const domain = '';//填你家的域名
const cron = '* * * * *';
const restartDelay = 5;
let previousIP = null; // 存储上一次解析的 IP 地址

export class duanwangchongqi extends plugin {
  constructor() {
    super({
      name: '断网重启检测',
      event: 'message',
      rule: [{ reg: '^#?断网检测', fnc: 'NetTest' }],
    });

    this.task = {
      name: '断网重启检测',
      cron: cron,
      fnc: () => {
        this.NetTest().then((r) => logger.mark('IP 检测完成'));
      },
    };
  }

  async NetTest() {
    try {
      dns.resolve4(domain, async (err, addresses) => {
        if (err) {
          console.error(`解析域名 ${domain} 出错: ${err.message}`);
          return;
        }

        const currentIP = addresses[0];

        if (previousIP && currentIP !== previousIP) {
          console.log(
            `IP 地址发生变化: ${previousIP} -> ${currentIP}. 执行重启...`
          );
          setTimeout(async () => {
            console.log('等待 10 分钟完成. 执行重启命令...');
            setTimeout(() => this.restart(), 2000); // 保持2秒后重启
            const ret = await Bot.exec('pnpm run restart');
            console.log(ret);
          }, restartDelay);
        } else {
          console.log(`IP 地址未变化: ${currentIP}`);
        }

        previousIP = currentIP; // 更新上一次解析的 IP 地址
      });
    } catch (error) {
      console.error(`IP 检测出错: ${error.message}`);
    }
  }

  restart() {
    console.log('执行 restart 方法... 尝试使用 Restart 类重启 (参考 update.js)');
    // 使用 Restart 类进行重启 (参考 update.js)
    // try {
    //    const restartInstance = new Restart(this.e);
    //    restartInstance.restart().then(r => console.log("重启ing"));
    //    console.log('Successfully called Restart.restart() from duanwangchongqi.restart() (参考 update.js).');
    // } catch (error) {
    //    console.error(`Error calling Restart.restart() from duanwangchongqi.restart() (参考 update.js): ${error}`);
    // }
  }
}
